﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Fly.Common.Linq;
using Newtonsoft.Json;
using Telerik.Web.UI;

namespace RN.ERP.Web.Person
{
    public partial class PersonEmpSafeCertList : BasePage
    {
            #region  公共属性
            /// <summary>
            /// 登陆用户guid
            /// </summary>
            protected string CorpUserGuid
            {
                get
                {
                    return UserInfo.CorpUserGuid;
                }
            }
            /// <summary>
            /// 当前市场
            /// </summary>
            protected string AreaCode
            {
                get
                {
                    return UserInfo.CurrentArea;
                }
            }
            /// <summary>
            /// 登陆用户类型
            /// </summary>
            protected string RoleType
            {
                get
                {
                    return UserInfo.RoleType;
                }
            }
            /// <summary>
            /// 登录用户roleid
            /// </summary>
            protected string RoleId
            {
                get
                {
                    return UserInfo.RoleId;
                }
            }
            /// <summary>
            /// 作为查询地区限定条件
            /// </summary>
            protected string AreaCodeWhere
            {
                get
                {
                    return UserInfo.AreaCode;
                }
            }
            /// <summary>
            /// 标识在管理端通过企业guid查询列表
            /// </summary>
            protected string tag
            {
                get
                {
                    return ViewState["tag"].ToString();
                }
            }
            /// <summary>
            /// 人员类型
            /// </summary>
            private int classId;

            #endregion
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    Initial();
                    CheckSystem();
                }
            }
            #region 页面设置
            /// <summary>
            /// 参数及设置按钮显示
            /// </summary>
            private void Initial()
            {
                LinkButton5.Visible = false;
                int opt = 0;//默认是一级页面
                string areaCode = string.Empty;
                string flowCode = string.Empty;
                ////人员类型
                if (Request.QueryString["classId"] != null)
                {
                    int.TryParse(Request.QueryString["classId"].Trim(), out classId);
                }
                hdClassId.Value = classId.ToString();

                //表示是否从统计页面来
                if (Request.QueryString["opt"] != null)
                {
                    int.TryParse(Request.QueryString["opt"].Trim(), out opt);
                }
                //统计页面参数-地区号
                if (Request.QueryString["areacode"] != null)
                {
                    areaCode = Request.QueryString["areacode"].Trim();
                }
                //统计页面参数-审核状态
                if (Request.QueryString["flowcode"] != null)
                {
                    flowCode = Server.UrlDecode(Request.QueryString["flowcode"].Trim());
                }
                ////证书类型
                if (Request.QueryString["itemType"] != null)
                {
                    FormatQueryParam(Request.QueryString["itemType"].Trim());
                }
                ViewState["opt"] = opt;
                ViewState["areaCode"] = areaCode;
                ViewState["flowCode"] = flowCode;
                ViewState["tag"] = 0;
                ///用户端登陆
                SetUsersShow();
                //企业Guid
                if (!string.IsNullOrEmpty(Request.QueryString["corpUserGuid"]))
                {
                    ViewState["tag"] = 1;//标识在通过企业guid查询列表
                    hdCorpUserGuid.Value = Request.QueryString["corpUserGuid"].Trim();
                }
            }
            /// <summary>
            /// 根据用户页配置面内容
            /// </summary>
            private void SetUsersShow()
            {
                if (RoleType == "User")
                {
                    UserDiv.Visible = true;//企业端操作按钮div
                    ///用户端登陆
                    hdCorpUserGuid.Value = CorpUserGuid;
                    return;
                }
                //企业端不显示的查询条件
                BindFlowCode();
                ManagerDiv.Visible = true;//管理端操作按钮
                lblCorpName.Visible = true;
                txtCorpName.Visible = true;
                dropEmpStatus.Visible = true;
                lblEmpFlow.Visible = true;
                if (ViewState["opt"].ToString() == "0" && dropEmpStatus.Items.Count >= 1)
                {
                    dropEmpStatus.SelectedIndex = 1;
                }
            }
            /// <summary>
            /// 取得证书类型参数--参数格式：x,x或1;x,x
            /// </summary>
            /// <param name="itemType"></param>
            private void FormatQueryParam(string itemType)
            {
                if (itemType.Contains(";"))
                {
                    hdEmpItemFlag.Value = itemType.Split(';')[0];
                    hdEmpItemType.Value = itemType.Split(';')[1];
                }
                else
                {
                    hdEmpItemType.Value = itemType;
                }

            }
            /// <summary>
            /// 加载审核状态下拉列表
            /// </summary>
            private void BindFlowCode()
            {
                string classId = hdClassId.Value;
                if (string.IsNullOrEmpty(classId) || classId == "0")
                {
                    classId = "2511";
                }
                var dic = UtilitiesTool.GetAllFlowStatus(classId, AreaCode, RoleId);
                dropEmpStatus.DataSource = dic;
                dropEmpStatus.DataTextField = "key";
                dropEmpStatus.DataValueField = "value";
                dropEmpStatus.DataBind();
            }

            /// <summary>
            /// 100系统特殊功能-锁定人员
            /// </summary>
            private void CheckSystem()
            {
                if (SystemID == "100")
                {
                    lbtnJiesuo.Visible = true;
                    lbtnSuoding.Visible = true;
                    rgPersonList.Columns[rgPersonList.Columns.Count - 1].Visible = true;
                }
            }

            #endregion

            #region 取得数据源
            /// <summary>
            /// 取得人员信息参数列表
            /// </summary>
            /// <returns></returns>
            private string GetQueryConditions()
            {
                //高级查询返回条件
                if (!string.IsNullOrEmpty(hdSearchEndStr.Value))
                {
                    return Server.HtmlDecode(hdSearchEndStr.Value);
                }
                //审核状态
                string flowCodes = dropEmpStatus.SelectedValue;
                //作为统计页面二级页
                if (ViewState["opt"].ToString() == "1")
                {
                    flowCodes = ViewState["flowCode"].ToString();
                }
                List<ModelService.QueryPersonInfoCondition> query = new List<ModelService.QueryPersonInfoCondition>();
                //管理端
                if (RoleType == "Manager")
                {
                    if (flowCodes != "")
                    {
                        string[] arry = flowCodes.Split('|');
                        foreach (string a in arry)
                        {
                            ModelService.QueryPersonInfoCondition queryCondition = GetQueryCondition(a);
                            query.Add(queryCondition);
                        }
                    }
                    else
                    {
                        //管理端全部不包含未上报
                        ModelService.QueryPersonInfoCondition queryCondition = GetQueryCondition("019");
                        query.Add(queryCondition);
                    }
                }
                else
                {
                    ModelService.QueryPersonInfoCondition queryCondition = GetQueryCondition(string.Empty);
                    query.Add(queryCondition);
                }
                return JsonConvert.SerializeObject(query);
            }
            /// <summary>
            /// 取得人员参数项
            /// </summary>
            /// <param name="flowCode"></param>
            /// <returns></returns>
            private ModelService.QueryPersonInfoCondition GetQueryCondition(string flowCode)
            {
                ///设置查询参数
                ModelService.QueryPersonInfoCondition queryCondition = new ModelService.QueryPersonInfoCondition();
                //queryCondition.TypeFlag = new ParameterValue<string> { V = "-1", O = OptEnum.Like };
                int.TryParse(hdClassId.Value, out classId);
                //人员类型
                if (classId > 0)
                {
                    queryCondition.ClassId = new ParameterValue<int?> { V = classId, O = OptEnum.Equal };
                }
                //审核状态
                if (!string.IsNullOrEmpty(flowCode))
                {
                    if (flowCode == "019")
                    {
                        //管理端全部不包含未上报
                        queryCondition.FlowCode = new ParameterValue<string> { V = flowCode, O = OptEnum.Like };
                    }
                    else
                    {
                        queryCondition.FlowCode = new ParameterValue<string> { V = flowCode, O = OptEnum.Equal };
                    }
                }
                //企业名称
                if (!string.IsNullOrEmpty(txtCorpName.Text.Trim()))
                {
                    queryCondition.corpName = new ParameterValue<string> { V = txtCorpName.Text.Trim(), O = OptEnum.Like };
                }
                //人员名称
                if (!string.IsNullOrEmpty(txtEmpName.Text.Trim()))
                {
                    queryCondition.Name = new ParameterValue<string> { V = txtEmpName.Text.Trim(), O = OptEnum.Like };
                }
                ///身份证
                if (!string.IsNullOrEmpty(txtEmpIdCard.Text.Trim()))
                {
                    queryCondition.IDCard = new ParameterValue<string> { V = txtEmpIdCard.Text.Trim(), O = OptEnum.Equal };
                }
                //统计传递地区
                if (!string.IsNullOrEmpty(ViewState["areaCode"].ToString()))
                {
                    if (ViewState["areaCode"].ToString().IndexOf("00") > 1)//本地
                    {
                        queryCondition.AreaCode = new ParameterValue<string> { V = ViewState["areaCode"].ToString().Replace("00", "").Trim(), O = OptEnum.StartWith };
                    }
                    else if (ViewState["areaCode"].ToString().IndexOf("99") > 1)//外地
                    {
                        queryCondition.AreaCode = new ParameterValue<string> { V = ViewState["areaCode"].ToString().Replace("99", "").Trim(), O = OptEnum.NotStartWith };
                    }
                    else if (ViewState["areaCode"].ToString().Trim().Length > 2)//查询子地区
                    {
                        queryCondition.AreaCode = new ParameterValue<string> { V = ViewState["areaCode"].ToString(), O = OptEnum.StartWith };
                    }
                }
                else
                {
                    /////子地区查询
                    if (RoleType == "Manager" && tag == "0")
                    {
                        if (AreaCodeWhere.Length > 2)//本地
                        {
                            queryCondition.AreaCode = new ParameterValue<string> { V = AreaCodeWhere, O = OptEnum.StartWith };
                        }
                    }
                }
                //证书类型包含多种类型的人员（hdEmpItemFlag=1标识不包含）
                if (!string.IsNullOrEmpty(hdEmpItemType.Value.Trim()) && hdEmpItemFlag.Value != "1")
                {
                    int code = 0;
                    var list = new List<ParameterValue<int>>();
                    var arrt = hdEmpItemType.Value.Trim().Split(',');
                    foreach (var a in arrt)
                    {
                        if (int.TryParse(a.Trim(), out code))
                        {
                            var area = new ParameterValue<int>() { O = OptEnum.Equal, V = code };
                            list.Add(area);
                        }
                    }
                    queryCondition.TypeFlags = new ParameterValues<int>()
                    {
                        Logic = LogicEnum.Or,
                        Values = list
                    };
                }
                //企业guid
                if (!string.IsNullOrEmpty(hdCorpUserGuid.Value.Trim()))
                {
                    Guid userGuid = Guid.Empty;
                    Guid.TryParse(hdCorpUserGuid.Value.Trim(), out userGuid);
                    queryCondition.CorpGuid = new ParameterValue<Guid> { V = userGuid, O = OptEnum.Equal };
                }
                return queryCondition;
            }
            /// <summary>
            /// 其他人员，取得被排除的人员类型信息
            /// </summary>
            /// <param name="empGuid"></param>
            /// <param name="areaCode"></param>
            private List<int> GetEmpCertList()
            {
                List<int> certList = new List<int>();
                if (hdEmpItemFlag.Value == "1" && !string.IsNullOrEmpty(hdEmpItemType.Value.Trim()))
                {
                    int temp = 0;
                    string[] list = hdEmpItemType.Value.Trim().Split(',');
                    foreach (string a in list)
                    {
                        if (int.TryParse(a, out temp))
                        {
                            certList.Add(temp);
                        }
                    }
                }
                return certList;
            }
            /// <summary>
            /// 绑定人员数据列表
            /// </summary>
            private void rgPersonDataBind()
            {
                int currentPageIndex = rgPersonList.CurrentPageIndex;
                int pageSize = rgPersonList.MasterTableView.PageSize;
                string result = string.Empty;
                try
                {
                    using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                    {
                        int cnt = 0;
                        string queryStr = GetQueryConditions();
                        List<int> certList = GetEmpCertList();
                        if (certList.Count > 0)
                        {
                            result = client.GetEmpManagerByCerts(currentPageIndex + 1, pageSize, queryStr, JsonConvert.SerializeObject(certList), AreaCode,out cnt);
                            rgPersonList.VirtualItemCount =cnt;
                            rgPersonList.DataSource = JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(result);
                            return;
                        }
                        result = client.GetEmpManagerByCerts(currentPageIndex + 1, pageSize, queryStr, string.Empty, AreaCode, out cnt);
                        rgPersonList.VirtualItemCount = cnt;
                        rgPersonList.DataSource = JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(result);
                    }
                }
                catch
                { }
            }
            /// <summary>
            /// 绑定查询列表
            /// </summary>
            private void PersonDataBind()
            {
                //将高级查询和统计查询条件置空
                hdSearchEndStr.Value = "";
                ViewState["opt"] = 0;
                ViewState["areaCode"] = "";
                ViewState["flowCode"] = "";
                rgPersonList.CurrentPageIndex = 0;
                rgPersonDataBind();
                rgPersonList.DataBind();
            }
            #endregion

            #region 事件处理

            /// <summary>
            /// 绑定人员信息
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void rgPersonList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
            {
                rgPersonDataBind();
            }
            /// <summary>
            /// 审核状态查询
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            //protected void dropEmpStatus_SelectedIndexChanged(object sender, EventArgs e)
            //{
            //    PersonDataBind();
            //}
            /// <summary>
            /// 修改人员
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void btnUpdatePerson_Click(object sender, EventArgs e)
            {
                string empGuid = GetSelCheck();
                if (string.IsNullOrEmpty(empGuid))
                {
                    RadWindowManager1.RadAlert("请选择要操作的项！", 300, 150, "提示", "");
                }
                if (empGuid.IndexOf(",") > 0)
                {
                    RadWindowManager1.RadAlert("只能选择一个修改项！", 300, 150, "提示", "");
                }
                string url = string.Format("PersonEmpInfo.aspx?empGuid={0}&typeFlag={1}", empGuid, "-1");

                Response.Redirect(url, true);
            }
            /// <summary>
            /// 条件查询
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void lbtnEmpSreach_Click(object sender, EventArgs e)
            {
                PersonDataBind();
            }
            /// <summary>
            /// 取得客户端选择的项
            /// </summary>
            /// <returns></returns>
            private string GetSelCheck()
            {
                string empGuid = string.Empty;
                foreach (GridDataItem item in rgPersonList.Items)
                {
                    System.Web.UI.HtmlControls.HtmlInputCheckBox box = (System.Web.UI.HtmlControls.HtmlInputCheckBox)item.FindControl("ckb");
                    if (box.Checked)
                    {
                        empGuid = box.Value.Trim() + ",";
                    }
                }
                if (empGuid.Length > 1)
                {
                    empGuid = empGuid.TrimEnd(',');
                }
                return empGuid;
            }

            /// <summary>
            /// 输出JSON格式数据到页面
            /// </summary>
            /// <param name="dataStr"></param>
            private void OutputData(string dataStr)
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Write(dataStr);
                HttpContext.Current.Response.End();
            }

            /// <summary>
            /// 客户端grid刷新
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
            {
                if (e.Argument == "Rebind")
                {
                    rgPersonList.MasterTableView.SortExpressions.Clear();
                    rgPersonList.MasterTableView.GroupByExpressions.Clear();
                    rgPersonList.Rebind();
                }

            }

            #endregion
    }
}